package logic

import (
	"context"
	"fmt"
	"login/model/mysql"

	"login/loginrpc/internal/svc"
	"login/loginrpc/loginrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginUserLogic {
	return &LoginUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginUserLogic) LoginUser(in *loginrpc.LoginUserRequest) (*loginrpc.LoginUserResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("用户名不存在,请重新输入")
	}

	if in.Password != user.Password {
		return nil, fmt.Errorf("密码不正确,请重新输入")
	}

	captcha, _ := mysql.Rdb.Get(l.ctx, "captKey"+in.Account).Result()
	if in.Captcha != captcha {
		return nil, fmt.Errorf("图形验证码不正确,请重新输入")
	}

	smscaptcha, _ := mysql.Rdb.Get(l.ctx, "SmsKey"+in.Account).Result()
	if in.SmsCaptcha != smscaptcha {
		return nil, fmt.Errorf("短信验证码不正确,请重新输入")
	}

	return &loginrpc.LoginUserResponse{
		UserId: int64(user.ID),
	}, nil
}
